<template>
  <div>
    <a-button type="primary" class="add" @click="addHouse" style="margin-left:15px" v-if="approve != 2"
      >新增户型</a-button
    >
    <div class="flex justify-end" v-if="approve != 2">
      <a-button class="space" type="primary" v-if="!!form[0].id && readOnly" @click="readOnly = false" v-action:update>
        修改
      </a-button>
      <a-button v-if="!!form[0].id && !readOnly" class="space" type="primary" @click="updata" v-action:update>
        保存
      </a-button>
    </div>
    <a-form-model
      ref="createHouse"
      :model="houseform"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      v-for="(houseform, i) in form"
      :key="i"
      class="box"
      :hideRequiredMark="true"
    >
      <div class="flex justify-between">
        <h1>户型{{ i + 1 }}</h1>
        <a-button type="primary" v-if="i != 0" @click="remove(i)">删除</a-button>
      </div>
      <a-form-model-item label="房屋类型：" prop="houseType" style="margin-left:-615px">
        <a-radio-group v-model="houseform.houseType" :disabled="readOnly && houseform.id ? true : false">
          <a-radio :value="item.value" v-for="item in houseTypes" :key="item.text">
            {{ item.text }}
          </a-radio>
          <a-input
            style="width:30%"
            v-model="others[i]"
            :disabled="houseform.houseType != '其他' || (readOnly && houseform.id) ? true : false"
          />
        </a-radio-group>
      </a-form-model-item>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="房屋个数：" prop="houseNum">
            <a-input-number
              v-model="houseform.houseNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="卧室个数：" prop="bedroomNum">
            <a-input-number
              v-model="houseform.bedroomNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="车库数目：" prop="garageNum">
            <a-input-number
              v-model="houseform.garageNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="车位数目：" prop="parkingNum">
            <a-input-number
              v-model="houseform.parkingNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="浴室数目：" prop="bathroomNum">
            <a-input-number
              v-model="houseform.bathroomNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="平均土地面积(平方米)：" prop="avgLand">
            <m-input-number
              v-model="houseform.avgLand"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="平均建筑面积(平方米)：" prop="avgFloor">
            <m-input-number
              v-model="houseform.avgFloor"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="平均估值：" prop="avgPrice">
            <m-input-number
              v-model="houseform.avgPrice"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="每平方米建筑面积单价：">
            <m-input-number :value="price(houseform.avgPrice, houseform.avgFloor)" disabled class="length" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="预售个数：" prop="preNum">
            <a-input-number
              v-model="houseform.preNum"
              :min="0"
              :precision="0"
              :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
              :parser="value => `${value}`.replace(/\$\s?|(,*)/g, '')"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="平均预售价格：" prop="prePrice">
            <m-input-number
              v-model="houseform.prePrice"
              class="length"
              :disabled="readOnly && houseform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <a-row>
      <a-col :span="12" style="width:30%" :offset="2">
        <a-form-model-item label="项目总价值(incl GST)：">
          <m-input-number :value="projectTotal" disabled class="length" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12" style="width:30%" :offset="2">
        <a-form-model-item label="总预售金额(incl GST)：">
          <m-input-number :value="totalCost" disabled class="length" />
        </a-form-model-item>
      </a-col>
    </a-row>
    <a-row>
      <a-col :span="12" style="width:30%" :offset="2">
        <a-form-model-item label="已收到按金：" prop="deposit">
          <m-input-number v-model="deposit" class="length" :disabled="readOnly && form[0].id ? true : false" />
        </a-form-model-item>
      </a-col>
    </a-row>

    <a-button v-if="!form[0].id ? true : false" class="space" type="primary" @click="onSubmit">
      下一步
    </a-button>
  </div>
</template>

<script>
import { houseTypes } from '@/dict'
import {
  createHouse,
  getHouse,
  updateHouseById,
  deleteHouse,
  createHistory,
  updateFinish,
  getDetailList
} from '@/api/common'
import NP from 'number-precision'
import { commonRule, dateRule } from '@/utils/rules'
export default {
  name: 'ProjectBuilding',
  data() {
    return {
      labelCol: { span: 11 },
      wrapperCol: { span: 13 },
      houseTypes,
      read: true,
      others: [''],
      deposit: '',
      readOnly: true,
      // Archive: 0,
      form: [
        {
          houseType: '土地',
          houseNum: '',
          bedroomNum: '',
          garageNum: '',
          parkingNum: '',
          bathroomNum: '',
          avgLand: '',
          avgFloor: '',
          avgPrice: '',
          preNum: '',
          prePrice: ''
        }
      ],
      rules: {
        houseType: [
          {
            required: true,
            validator: (r, v, cb) => {
              if (v == 5 && !this.others) {
                cb(new Error('请输入其他'))
              } else {
                cb()
              }
            },
            message: '请输入',
            trigger: 'blur'
          }
        ],
        houseNum: commonRule,
        bedroomNum: commonRule,
        garageNum: commonRule,
        parkingNum: commonRule,
        bathroomNum: commonRule,
        avgLand: commonRule,
        avgFloor: commonRule,
        avgPrice: commonRule,
        preNum: commonRule,
        prePrice: commonRule
      }
    }
  },
  computed: {
    approve() {
      return Number(this.$route.query.approve)
    },
    // 项目总价值
    projectTotal() {
      var a = 0
      this.form.forEach(el => {
        a = NP.plus(a, NP.times(el.houseNum, el.avgPrice))
      })
      return a
    },
    //总预售金额
    totalCost() {
      var a = 0
      this.form.forEach(el => {
        a = NP.plus(a, NP.times(el.preNum || 0, el.prePrice || 0))
      })
      return a
    }
  },
  watch: {
    form: {
      handler(v) {
        let id = this.$route.query.id
        this.$store.commit('form/SAVE_DATA', {
          key: 'business/ProjectBuilding-' + id,
          value: this.form
        })
      },
      deep: true
    }
  },
  mounted() {
    let id = this.$route.query.id
    if (id) {
      this.getData()
    }
    if (!this.form.id) {
      const formStore = this.$store.state.form?.['business/ProjectBuilding-' + id]
      formStore && Object.assign(this.form, formStore)
    }
  },
  methods: {
    price(a, b) {
      if (b) {
        return NP.divide(a, b).toFixed(2)
      } else {
        return 0
      }
    },
    remove(i) {
      if (this.form[i].id) {
        const id = this.form[i].id
        deleteHouse(id)
      }
      this.form.splice(i, 1)
    },
    async getData() {
      let id = this.$route.query.id
      // const r = await getDetailList(id)
      // this.Archive = r.result.data.Archive
      const res = await getHouse(id, 1)
      let data = res.result.data
      this.deposit = data[0]?.deposit
      data.forEach((el, i) => {
        if (el.houseType != '土地' && el.houseType != '独栋' && el.houseType != '连排' && el.houseType != '公寓') {
          this.others[i] = el.houseType
          el.houseType = '其他'
        }
      })
      if (data.length) {
        this.form = data
      }
    },
    addHouse() {
      this.form.push({
        houseType: '土地',
        houseNum: '',
        bedroomNum: '',
        garageNum: '',
        parkingNum: '',
        bathroomNum: '',
        avgLand: '',
        avgFloor: '',
        avgPrice: '',
        avgFloorPrice: '',
        preNum: '',
        prePrice: ''
      })
      this.others.push('')
    },
    async onSubmit() {
      let projectId = this.$route.query.id
      let houseValid = false
      if (!this.deposit && this.deposit != 0) {
        this.$message.info('请输入')
        return
      }
      this.form.forEach((el, i) => {
        this.$refs.createHouse?.[i]?.validate(v => (houseValid = v))
        el.projectId = projectId
        el.deposit = this.deposit
      })
      if (houseValid) {
        var _new = []
        var _form = []
        this.form.forEach((el, i) => {
          if (el.houseType != '土地' && el.houseType != '独栋' && el.houseType != '连排' && el.houseType != '公寓') {
            el.houseType = this.others[i]
          }
        })
        this.form.forEach(el => {
          if (!el.id) {
            _new.push(el)
          }
        })
        if (_new.length != 0) {
          await createHouse({ houseList: _new })
          await updateFinish({ projectId: this.$route.query.id })
        }
        this.$store.commit('form/CLEAR', 'business/ProjectBuilding-' + projectId)
        this.$emit('submit')
      }
    },
    updata() {
      let projectId = this.$route.query.id
      let houseValid = false
      if (!this.deposit && this.deposit != 0) {
        this.$message.info('请输入')
        return
      }
      this.form.forEach((el, i) => {
        this.$refs.createHouse?.[i]?.validate(v => (houseValid = v))
        el.projectId = projectId
        el.deposit = this.deposit
      })
      if (houseValid) {
        var _new = []
        var _form = []
        this.form.forEach((el, i) => {
          if (el.houseType != '土地' && el.houseType != '独栋' && el.houseType != '连排' && el.houseType != '公寓') {
            el.houseType = this.others[i]
          }
        })
        this.form.forEach(el => {
          if (!el.id) {
            _new.push(el)
          } else {
            _form.push(el)
          }
        })
        if (_form.length != 0) {
          updateHouseById({ houseList: _form })
          const history = {
            recordType: 0,
            tableId: Number(projectId)
          }
          createHistory(history)
        }
        if (_new.length != 0) {
          createHouse({ houseList: _new })
        }
        this.$store.commit('form/CLEAR', 'business/ProjectBuilding-' + projectId)
      }
      this.readOnly = true
    }
  }
}
</script>

<style>
.length {
  width: 200px;
}
.space {
  margin-left: 45%;
}
.box {
  clear: both;
  border: 1px solid rgb(184, 182, 182);
  padding: 15px;
  margin: 25px;
  border-radius: 10px;
}
</style>
